package userdao

import (
	"itodo/core/dao/table"
	"itodo/core/service/common"

	"strconv"

	"github.com/RocksonZeta/wrap/redised"
	"github.com/RocksonZeta/wrap/utils/sutil"
	"github.com/RocksonZeta/wrap/utils/timeutil"
)

type Users struct {
	*redised.RedisedMysql
}

func (s Users) redisKey(id int) string {
	return "User/" + strconv.Itoa(id)
}

func (s Users) ClearCache(id int) {
	s.Redis.Del(s.redisKey(id))
}

type UsersQueryParam struct {
	common.Page
	Name string
}

//Query 根据条件查询
func (s Users) Query(param UsersQueryParam) ([]table.User, int64) {
	wsql := " from User where 1=1"
	if param.Name != "" {
		param.Name = "%" + param.Name + "%"
		wsql += " and name like :Name"
	}
	ssql := "select *" + wsql + " order by ct desc" + param.Limit()
	csql := "select count(*)" + wsql
	var r []table.User
	s.Mysql.Select(&r, ssql, param)
	return r, s.Mysql.SelectInt(csql, param)
}

func (s Users) Get(id int) table.User {
	var r table.User
	s.RedisedMysql.Get(&r, "User", "Id", id)
	return r
}
func (s Users) GetByEmail(email string) table.User {
	var r table.User
	s.RedisedMysql.GetByKvs(&r, "User", "Id", sutil.M{"email": email})
	return r
}

func (s Users) List(ids []int) []table.User {
	var r []table.User
	s.RedisedMysql.List(&r, "User", "Id", ids)
	return r
}

type UsersAddParam struct {
	Name string
}

func (s Users) Add(param UsersAddParam) table.User {
	var t table.User
	sutil.Copy(param, &t)
	t.Ct = timeutil.Now()
	s.Mysql.AddTable(t)
	s.Mysql.Insert(&t)
	s.ClearCache(t.Id)
	return t
}

type UsersUpdateParam struct {
	Id   int
	Name string
}

func (s Users) Update(param UsersUpdateParam) {
	s.Mysql.Patch("User", "Id", param)
	s.ClearCache(param.Id)
}

func (s Users) Delete(id int) {
	s.Mysql.Delete("User", "Id", id)
	s.ClearCache(id)
}

